package logic

import (
	"context"
	"encoding/json"
	"pet-adopt-hub/cache"
	"pet-adopt-hub/models"
	"time"

	"pet-adopt-hub/petrpc/internal/svc"
	"pet-adopt-hub/petrpc/petrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListLogic {
	return &ListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListLogic) List(in *petrpc.ListRequest) (*petrpc.ListResponse, error) {
	// todo: add your logic here and delete this line
	key := "list"
	var petdata []models.PetData
	cachejson, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	if cachejson == "" {
		models.DB.Debug().
			Table("pets").
			Joins("left join styles on pets.style_id=styles.id").
			Joins("left join people on pets.person_id=people.id").
			Select("pets.*",
				"styles.name as StyleName",
				"people.name as PersonName").
			Find(&petdata)
		cachedata, _ := json.Marshal(petdata)
		cache.Rdb.Set(cache.Ctx, key, cachedata, time.Hour*1)
	} else {
		json.Unmarshal([]byte(cachejson), &petdata)
	}
	var lists []*petrpc.List
	for _, data := range petdata {
		list := &petrpc.List{
			Name:     data.Name,
			Sex:      data.Sex,
			Context:  data.Context,
			StyleId:  int64(data.StyleId),
			PersonId: int64(data.PersonId),
			PetId:    int64(data.ID),
		}
		lists = append(lists, list)
	}
	return &petrpc.ListResponse{
		List: lists,
	}, nil
}
